<script setup>
import {ref, onMounted, computed} from 'vue';
import {useLogStore} from "@/stores/logStore.js";
import LogDetail from "@/views/account/LogDetail.vue";
import LogArchive from "@/views/account/LogArchive.vue";
import LogStatistics from "@/views/account/LogStatistics.vue";

import {ElMessageBox} from 'element-plus'

import {LogApi} from "@/api/log/index.js";

const logStore = useLogStore();
const logDetailRef = ref(null);
const logArchiveRef = ref(null);
const logStatisticsRef = ref(null);

// 初始化加载日志列表
onMounted(() => {
  logStore.getLogList();
});

// 处理分页变化
const handleCurrentChange = (page) => {
  logStore.handlePageChange(page);
};

// 查看日志详情
const handleDetail = (logId) => {
  logDetailRef.value.show(logId);
};

// 打开归档对话框
const handleArchive = () => {
  logArchiveRef.value.show();
};

// 打开统计对话框
const handleStatistics = () => {
  logStatisticsRef.value.show();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString();
};

// 格式化日志详情
const formatDetail = (detail) => {
  try {
    const parsed = JSON.parse(detail);
    return typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : detail;
  } catch {
    return detail;
  }
};

// 搜索日志
const handleSearch = () => {
  logStore.pageInfo.page = 1; // 重置为第一页
  logStore.getLogList();
};

// 重置搜索条件
const handleReset = () => {
  logStore.resetQueryParams();
  logStore.getLogList();
};

//日志导出
const handleExport = async () => {
  try {
    await logStore.exportLogs();
  } catch (error) {
    ElMessageBox.alert(
        '如果导出失败请查询：<a href="http://localhost:8080/api/log/export" target="_blank">点击查看</a>',
        '导出提示',
        {
          dangerouslyUseHTMLString: true,
          type: 'success'
        }
    );
  }
};


</script>

<template>
  <div class="log-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="logStore.queryParams" class="search-form">
        <el-form-item label="用户ID">
          <el-input v-model.number="logStore.queryParams.userId" placeholder="用户ID" clearable />
        </el-form-item>

        <el-form-item label="操作类型">
          <el-input v-model="logStore.queryParams.action" placeholder="操作类型" clearable />
        </el-form-item>

        <el-form-item label="目标类型">
          <el-input v-model="logStore.queryParams.targetType" placeholder="目标类型" clearable />
        </el-form-item>

        <el-form-item label="目标ID">
          <el-input v-model.number="logStore.queryParams.targetId" placeholder="目标ID" clearable />
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
              v-model="logStore.queryParams.startTime"
              type="datetime"
              placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span class="time-separator">至</span>
          <el-date-picker
              v-model="logStore.queryParams.endTime"
              type="datetime"
              placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="operation-buttons">
        <el-button type="primary" @click="handleArchive">日志归档</el-button>
        <el-button type="success" @click="handleExport">导出日志</el-button>
        <el-button type="info" @click="handleStatistics">统计报表</el-button>
      </div>
    </div>

    <!-- 日志表格 -->
    <el-table :data="logStore.logList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="action" label="操作类型" width="150" />
      <el-table-column prop="targetType" label="目标类型" width="120" />
      <el-table-column prop="targetId" label="目标ID" width="100" />

      <el-table-column label="变更详情" width="200">
        <template #default="{ row }">
          <el-popover placement="top-start" width="500" trigger="hover">
            <template #reference>
              <el-button type="text">{{ row.detail ? '查看详情' : '无详情' }}</el-button>
            </template>
            <pre style="max-height: 300px; overflow: auto;">{{ formatDetail(row.detail) }}</pre>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column prop="ip" label="IP地址" width="150" />

      <el-table-column label="操作时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createdTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleDetail(row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="logStore.pageInfo.page"
          :page-size="logStore.pageInfo.size"
          :total="logStore.pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 日志详情对话框 -->
    <LogDetail ref="logDetailRef" />

    <!-- 日志归档对话框 -->
    <LogArchive ref="logArchiveRef" />

    <!-- 统计报表对话框 -->
    <LogStatistics ref="logStatisticsRef" />
  </div>
</template>

<style scoped>
.log-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-separator {
  margin: 0 10px;
  color: #606266;
}

.operation-buttons {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>